package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.AddressBook;
import com.itheima.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 地址簿管理
 */
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    /**
     * 新增收货地址
     *
     * @param addressBook
     * @return
     */
    @PostMapping
    public R<AddressBook> save(@RequestBody AddressBook addressBook) {
        //先从ThreadLocal中去到当前用户id，然后放回addressBook中
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        System.out.println("addressBook的值：" + addressBook);
        try {
            addressBookService.save(addressBook);
        } catch (Exception e) {
            e.getMessage();
        }
        return R.success(addressBook);
    }

    /**
     * 查询所有地址
     * 这里操作了两次数据库，最好就是写在service层里面再加个@Transactional事务管理
     *
     * @return
     */
    @GetMapping("/list")
    public R<List<AddressBook>> list(AddressBook addressBook) {
        //先从ThreadLocal中去到当前用户id，然后放回addessBook中
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //设置条件构造器
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(addressBook.getUserId() != null, AddressBook::getUserId, addressBook.getUserId());
        //按更新时间降序排序
        queryWrapper.orderByDesc(AddressBook::getUpdateTime);
        //执行查询
        List<AddressBook> list = addressBookService.list(queryWrapper);
        if (list == null) {
            return R.error("查询地址失败");
        }
        return R.success(list);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping("/default")
    public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
        //先从ThreadLocal中去到当前用户id，然后放回addressbook中
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //设置更新条件构造器，LambdaUpdateWrapper
        LambdaUpdateWrapper<AddressBook> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AddressBook::getUserId, addressBook.getUserId());
        updateWrapper.set(AddressBook::getIsDefault, 0);
        //先将用户所有的收货地址改为非默认，就是把所有收货地址的is_default字段设置为0，避免了存在多个默认地址的问题
        //update address_book set is_default = 0 where user_id = ?
        addressBookService.update(updateWrapper);

        //再将前端传进来的那一条收货地址设置为默认地址
        addressBook.setIsDefault(1);
        //update addrress_book set is_default = 1 where id = ?
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    /**
     * 用户修改地址回显数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id) {
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook == null) {
            return R.error("用户地址回显失败");
        }
        return R.success(addressBook);
    }

    /**
     * 用户修改地址
     *
     * @param addressBook
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        boolean result = addressBookService.updateById(addressBook);
        if (!result) {
            return R.error("修改用户地址失败");
        }
        return R.success("修改用户地址成功");
    }

    /**
     * 根据id删除用户地址
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {
        boolean result = addressBookService.removeBatchByIds(ids);
        if (!result) {
            return R.error("删除用户地址失败");
        }
        return R.success("删除用户地址成功");
    }

    /**
     * 查询默认地址，用于订单明细展示
     *
     * @return
     */
    @GetMapping("/default")
    public R<AddressBook> getDefault() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
        queryWrapper.eq(AddressBook::getIsDefault, 1);
        AddressBook addressBook = addressBookService.getOne(queryWrapper);
        if (addressBook == null) {
            return R.error("没有找到默认地址");
        }
        return R.success(addressBook);
    }

}
